#include"Heap.h"

void AdjustDwon(heapdata* a, int parent, int size)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size && a[child] > a[child + 1])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void AdjustUp(heapdata* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HpInit(HP* hp)
{
	assert(hp);
	hp->arr = NULL;
	hp->capacity = hp->size = 0;
}

void DestoryHeap(HP* hp)
{
	assert(hp);
	free(hp->arr);
	hp->capacity = hp->size = 0;
}
void HPPush(HP* hp, heapdata x)
{
	assert(hp);
	if (hp->capacity == hp->size)
	{
		int newcapacity = hp->capacity == 0 ? 4 : 2 * hp->capacity;
		heapdata* tmp = (heapdata*)realloc(hp->arr, sizeof(heapdata) * newcapacity);
		if (tmp == NULL)
		{
			perror("malloc fail");
			exit(-1);
		}
		hp->arr = tmp;
		hp->capacity = newcapacity;
	}
	hp->arr[hp->size] = x;
	AdjustUp(hp->arr, hp->size);
	++hp->size;
}

heapdata HPTop(HP* hp)
{
	assert(hp);
	return hp->arr[0];
}

void HPPop(HP* hp)
{
	assert(hp);
	Swap(&(hp->arr[0]), &(hp->arr[hp->size - 1]));
	--hp->size;
	AdjustDwon(hp->arr, 0, hp->size);
}
